<?php

namespace App\Http\Middleware;

use App\Models\Member;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Facades\JWTAuth;

class CheckMemberToken
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $token = JWTAuth::getToken();
            if (empty($token)) {
                return response()->json(['code' => 40001, 'message' => '未登录', 'data' => []], 401);
            }

            $sub = JWTAuth::setToken($token)->getPayload()->get('sub');
            if ($sub) {
                $user = Member::where(['id' => $sub, 'status' => 1])->first();
                if (!$user) {
                    return response()->json(['code' => 40002, 'message' => '您的账号已被锁定，如有疑问请联系客服', 'data' => []], 401);
                }
            }
            return $next($request);
        } catch (TokenExpiredException $e) {
            try {
                $token = JWTAuth::refresh();
                if ($token) {
                    return response()->json(['code' => 40003, 'message' => '新token', 'data' => ['access_token' => 'Bearer ' . $token]], 403);
                }
            } catch (JWTException $e) {
                return response()->json(['code' => 40001, 'message' => '登录状态已失效,请重新登录', 'data' => []], 401);
            }
        }
    }
}
